<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


App::import('Model', 'Account');

class tattlrAccountsController extends AppController {

    public $helpers = array('Html', 'Form');
	
    public function index() {

       $accountsArray = $this->tattlrAccount->getAllaccountsDelete();
        $length = count($accountsArray);
        $caller = $this->Auth->user('userID');
        $user = new User();
        $admin = $user->isAdmin($caller);
        $images = array();
        for ($i = 0; $i < $length; $i++) {
            $result = (ClassRegistry::init('Account')->find('all', array('conditions' => array('Account.accID' => $accountsArray[$i]['Accounts']['accID']), 'fields' => 'Account.image')));
            if ($result[0]['Account']['image'] == null) {
                $images[$i] = 'eggs.png';
            } else {
                $images[$i] = $result[0]['Account']['image'];
            }
        }
        //print_r($images);
        if ($admin == 1) {
		if (isset($_SESSION['account']) && isset($_SESSION['limit'])) {
                $this->set('account', $_SESSION['account']);
                $this->set('limit', $_SESSION['limit']);
                unset($_SESSION['account']);
                unset($_SESSION['limit']);
            }
            $this->set('images', $images);
            $this->set('admin', $admin);
            //send the parameters to the view
            $this->set('caller', $caller);
            $this->set('accountsArray', $accountsArray);
            $this->set('length', $length);
            $this->set('l', $length);
        } else {
            $this->Session->setFlash('you are not authorized to view this page');
        }
    }
public function checkLimit($accountid=null) {
        $con = ClassRegistry::init('Account')->connectionRequest($accountid);
        $content = $con->get('account/rate_limit_status');
        $_SESSION['account'] = $accountid;
        $_SESSION['limit'] = $content->remaining_hits;
        $this->redirect(array('controller' => 'tattlraccounts', 'action' => 'index'));
    }
	/**
     * this function reactivates a twitter account in case access to it has been revoked .
     * @param $accountid
	 * @return void
     * @author "Omar Ruedy"
     */
	public function reactivate($accountid=null) {
        if (!(ClassRegistry::init('User')->isAdmin($this->Auth->user()))) {
            $this->Session->setFlash('NOT ADMIN!');
            return;
        }
        if ($accountid != null) {
            $_SESSION['accID'] = $accountid;
            $twitteroauth = new TwitterOAuth('S9Ww3avoaAONgzqU27DKMQ', 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw');
            $request_token = $twitteroauth->getRequestToken('http://localhost/tattlraccounts/reactivate');
            unset($_SESSION['oauth_token']);
            unset($_SESSION['oauth_token_secret']);
            $_SESSION['oauth_token'] = $request_token['oauth_token'];
            $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
            if ($twitteroauth->http_code == 200) {
                $redirect_url = $twitteroauth->getAuthorizeURL($request_token, false);
                $this->redirect($redirect_url);
            } else {
                $this->Session->setFlash('OH boy,I think something is wrong with your internet connection!');
            }
        } else {
            $connection = new TwitterOAuth('S9Ww3avoaAONgzqU27DKMQ', 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw', $_SESSION['oauth_token'],
                            $_SESSION['oauth_token_secret']);
            $token_credentials = $connection->getAccessToken($_REQUEST['oauth_verifier']);
            $content = $connection->get('account/verify_credentials');
            if (!empty($token_credentials['oauth_token']) && !empty($token_credentials['oauth_token_secret'])) {
                if ($_SESSION['accID'] == $token_credentials['user_id']) {
                    $oauthToken = $token_credentials['oauth_token'];
                    $oauthSecret = $token_credentials['oauth_token_secret'];
                    $this->tattlrAccount->updateAll(
                            array('oauthToken' => "'$oauthToken'", 'oauth_token_secret' => "'$oauthSecret'"), array('accID' => $token_credentials['user_id']));
                    $this->Session->setFlash('Account Successfully Reactivated!');
                } else {
                    $this->Session->setFlash('You logged in with a different account then the one you requested to reactivate!');
                }
            } else {
                $this->Session->setFlash('Could not reactivate account,please try again!');
            }
        }
        $this->redirect(array('controller' => 'tattlraccounts', 'action' => 'index'));
    }
    /*
     * Twitter will redirect the user to this page when authorization is successful.The method also adds the account to the db,in table accounts and table and tattlr_accounts.    
     * @return void
     * @author "Omar Ruedy"
     */

    public function Proceed() {

        $connection = new TwitterOAuth('S9Ww3avoaAONgzqU27DKMQ', 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw', $_SESSION['oauth_token'],
                        $_SESSION['oauth_token_secret']);
        $tmpAccount = new Account();
        $token_credentials = $connection->getAccessToken($_REQUEST['oauth_verifier']);
        $content = $connection->get('account/verify_credentials');
        $image = $content->profile_image_url;
        if (!empty($token_credentials['oauth_token']) && !empty($token_credentials['oauth_token_secret'])) {
            if (!($tmpAccount->isUnique('accID', $token_credentials['user_id'])) && !($this->tattlrAccount->isUnique('accID', $token_credentials['user_id'])) && ($this->tattlrAccount->checkIfAccountExistsAndNotDeleted($token_credentials['user_id'])) == true) {

                $this->Session->setFlash('This account already exists,you just choose a different name ;)');
            } else {
                if (!($tmpAccount->isUnique('accID', $token_credentials['user_id'])) && !($this->tattlrAccount->isUnique('accID', $token_credentials['user_id'])) && ($this->tattlrAccount->checkIfAccountExistsAndNotDeleted($token_credentials['user_id'])) == false) {
                    $accName = $_SESSION['name'];
                    $oauthToken = $token_credentials['oauth_token'];
                    $oauthSecret = $token_credentials['oauth_token_secret'];
                    $tmpAccount->updateAll(
                            array('name' => "'$accName'", 'image' => "'$image'"), array('accID' => $token_credentials['user_id']));
                    $this->tattlrAccount->updateAll(
                            array('isDeleted' => 0, 'oauthToken' => "'$oauthToken'", 'oauth_token_secret' => "'$oauthSecret'"), array('accID' => $token_credentials['user_id']));
                    $this->Session->setFlash('Account Successfully Added!');
                } else {
                    if ((!($tmpAccount->isUnique('accID', $token_credentials['user_id']))) && ($this->tattlrAccount->isUnique('accID', $token_credentials['user_id']))) {
                        $accName = $_SESSION['name'];
                        $tmpAccount->updateAll(
                                array('name' => "'$accName'", 'image' => "'$image'"), array('accID' => $token_credentials['user_id']));
                        $this->tattlrAccount->set(array('accID' => $token_credentials['user_id'], 'isDeleted' => '0', 'minDuaration' => '1', 'oauthToken' => $token_credentials['oauth_token'], 'oauth_token_secret' => $token_credentials['oauth_token_secret'], 'last_tweet' => '220476133647466496'));
                        $this->tattlrAccount->save();
                        $this->Session->setFlash('Account Successfully Added!');
                    } else {

                        $tmpAccount->set(array('accID' => $token_credentials['user_id'], 'twitterName' => $token_credentials['screen_name'], 'name' => $_SESSION['name'], 'image' => $image));
                        $tmpAccount->save();
                        $this->tattlrAccount->set(array('accID' => $token_credentials['user_id'], 'isDeleted' => '0', 'minDuaration' => '1', 'oauthToken' => $token_credentials['oauth_token'], 'oauth_token_secret' => $token_credentials['oauth_token_secret'], 'last_tweet' => '220476133647466496'));
                        $this->tattlrAccount->save();
                        $this->Session->setFlash('Account Successfully Added!');
                    }
                }
            }
        } else {
            $this->Session->setFlash('Could not add account,please try again!');
        }
		$this->redirect(array('controller' => 'tattlraccounts', 'action' => 'index'));
    }
	/**
     * this function gets the id of the currently selected account and sets it in the db , table users , in the filed of accID of the current logged in user .
	 * @return void
     * @author "Omar Ruedy"
     */
    public function selectAccount() {
        if (!empty($this->request->data)) {
            $ACCID = ClassRegistry::init('Account')->getAccountIdByName(($this->request->data['tattlrAccount']['Account']));
            ClassRegistry::init('User')->updateUserWithAccId($this->Auth->User('userID'), $ACCID[0]['Account']['accID']);
            $data['User'] = $this->Auth->user();
            $data['User']['accID'] = $ACCID[0]['Account']['accID'];
            $this->Session->write("Auth", $data);
            $this->redirect($this->referer());
        }
    }

    /*
     * This method is responsible for the view to add clients.It asks twitter for an auth token and auth secret and adds them to session .And if the request was successful it will redirect to the proceed page.     
     * @return void
     * @author "Omar Ruedy"
     */
    public function addaccount() {
        $this->set('admin', ClassRegistry::init('User')->isAdmin($this->Auth->user()));
        if (!(ClassRegistry::init('User')->isAdmin($this->Auth->user()))) {
            $this->Session->setFlash('NOT ADMIN!');
        } else {

            if (!empty($this->request->data)) {
                if (empty($this->request->data['tattlrAccount']['AccountName'])) {
                    $this->Session->setFlash('Account Name cannot be empty!');
                } else {
                    $tmpAccount = new Account();
                    if (!($tmpAccount->isUnique('name', $this->data['tattlrAccount']['AccountName'])) && $this->tattlrAccount->checkIfAccountExists($this->data['tattlrAccount']['AccountName'])) {
                        $this->Session->setFlash('Name already exists!');
                    } else {
                        $twitteroauth = new TwitterOAuth('S9Ww3avoaAONgzqU27DKMQ', 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw');
                        $request_token = $twitteroauth->getRequestToken('http://localhost/tattlraccounts/proceed');
                        $_SESSION['oauth_token'] = $request_token['oauth_token'];
                        $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
                        $_SESSION['name'] = $this->request->data['tattlrAccount']['AccountName'];
                        if ($twitteroauth->http_code == 200) {
                            $redirect_url = $twitteroauth->getAuthorizeURL($request_token, false);

                            $this->redirect($redirect_url);
                        } else {
                            $this->Session->setFlash('OH boy,I think something is wrong with your internet connection!');
                        }
                    }
                }
            }
        }
    }

    /**
     * This method sends the accounts list to the view and  the caller of the delete function
     *
     * @access: public
     * @param: array $accountsArray; 3d array of the non deleted accounts IDs
     * @param: int $length; the number of non deleted accounts
     * @param: int $caller; the user ID of the signed in user
     * @author "Mina Farag"
     */
    public function delete() {
        $accountsArray = $this->tattlrAccount->getAllaccountsDelete();
        $length = count($accountsArray);
        $caller = $this->Auth->user('userID');
        $user = new User();
        $admin = $user->isAdmin($caller);
        if ($admin == 1) {
            $this->set('admin', $admin);
            //send the parameters to the view
            $this->set('caller', $caller);
            $this->set('accountsArray', $accountsArray);
            $this->set('length', $length);
            $this->set('l', $length);
        } else {
            $this->Session->setFlash('you are not authorized to view this page');
        }
    }

    /**
     * This method calls the deleteAccount function from the tattlraccount model
     *
     * @access: public
     * 
     * @param: int $accountID; the account i want to delete
     * @param: int $caller; the user ID of the signed in user
     * @author "Mina Farag"
     */
    public function delete1($accountid) {

        $caller = $this->Auth->user('userID');
        //call the deleteAccount function from the model 
        $message = $this->tattlrAccount->deleteAccount($caller, $accountid);
        //set the deletion status message linked to the dash board URL
        $this->redirect('/tattlraccounts');
    }

    function db() {
        $this->tattlrAccount->ddb();
    }

}
?>

